package com.naiterui.ehp.bs.doctor.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;
import com.naiterui.ehp.bp.utils.encypt.AESUtil;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;

import java.nio.charset.StandardCharsets;

/**
 * URL相关方法
 * @Author xudong

 */
public class UrlUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlUtil.class);

    /**
     * <p>Description:将保存宣教的url地址中的中文转换为对应的encode值 </p>
     * @Author xudong

     * @date 2017年12月4日
     * @since 1.0.0
     * @param url
     * @return
     */
    public static String urlEncode(String url) {
        // 转换为%E4%BD%A0形式
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < url.length(); i++) {
            char c = url.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = String.valueOf(c).getBytes(StandardCharsets.UTF_8);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                    b = new byte[0];
                }
                for (byte aB : b) {
                    int k = aB;
                    if (k < 0) {
                        k += 256;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 医脉通视频,url token补全
     * @param url
     * @return
     */
    public static String medliveConvert(String url, Long doctorId) {

        String result = url;
        String aesKey = ConfigUtil.getString("medlive.aes.key");
        String urlPrefix = ConfigUtil.getString("medlive.url.prefix");
        String tokenSuffix = ConfigUtil.getString("medlive.token.suffix");

        if (StringUtils.isNotEmpty(url) && url.startsWith(urlPrefix)) {
            result = url + "?token=" + AESUtil.encryptURLencode(aesKey, doctorId + tokenSuffix);
        }
        return result;
    }
}
